package com.mrd.util;

import com.alibaba.fastjson.JSONObject;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by dengdc on 2017/7/19.
 */
public class WeiChatUtil {
    private static final String KEY_OPEN_ID = "openid";

    /**
     * {"access_token":"DMM1pyBjTxRBTOAwphjPIgmRRvoLfix8VosCHss9fGyfzR2gfwIPS-yif_LDAhLsVG0crohPBMm_LiZobewMVclKU9-sHmWCdgJW9kXg3Qg","expires_in":7200,"refresh_token":"PhQnV1Wu7AyzWYSdtXMcXPoO9_4uuB89UiQX7OCRJouP9BXNz6lBOjbb7u56SUN0WdhZKZ8cDZfXbGULb2N9_de1bjb4Ul2O1t1TIIIrR3Y","openid":"oqNcwwENemIqOucIopl1jAh9psM8","scope":"snsapi_base"}
     * @param code
     * @return
     */
    public static String getOpenidFromWeChatServer(String code){
        HttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost=new HttpPost("https://api.weixin.qq.com/sns/oauth2/access_token");//HTTP Get请求(POST雷同)
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("appid","wx687b4a4176f16b90"));
        nvps.add(new BasicNameValuePair("secret","8712c46756858f90dc562ec1bf98c8b1"));
        nvps.add(new BasicNameValuePair("code",code));
        nvps.add(new BasicNameValuePair("grant_type","authorization_code"));
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nvps,"utf-8"));
            HttpResponse response = httpClient.execute(httpPost);
            String jsonString = EntityUtils.toString(response.getEntity());
            System.out.println(jsonString);
            JSONObject jsonObject = JSONObject.parseObject(jsonString);
            if(jsonObject.containsKey(KEY_OPEN_ID)){
                return jsonObject.getString(KEY_OPEN_ID);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static void main(String[] args){
        WeiChatUtil.getOpenidFromWeChatServer("021Has7h1yXTDw0Jqb4h1mFs7h1Has7L");
    }
}
